<template>
    <div>
        <van-nav-bar
                title="添加订单"
                left-text="返回"
                left-arrow
                @click-left="onBack"
        />

        <group>
            <datetime
                    v-model="jhrq"
                    @on-cancel="dateCancel"
                    placeholder="请选择交货日期"
                    title="交货日期"></datetime>

            <van-cell
                    center
                    title="客户名称"
                    @click="focusKh"
                    size="large"
            >
                <el-select
                        ref="khmcRef"
                        v-model="khbh"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词"
                        :remote-method="customerList"
                        :loading="khLoading">
                    <el-option
                            v-for="item in khOptions"
                            :key="item.khbh"
                            :label="item.khmc"
                            :value="item.khbh">
                    </el-option>
                </el-select>
            </van-cell>
            <popup-picker title="付款方式" :data="fkfsOptions" v-model="fkfs" placeholder="请选择付款方式"></popup-picker>
            <van-cell-group>
                <van-field
                        v-model="bz"
                        label="备注"
                        type="textarea"
                        placeholder="请输入备注"
                        rows="1"
                        autosize
                />
            </van-cell-group>
            <van-cell center>
                <van-row>
                    <van-col span="8">数量合计: {{slhj}}</van-col>
                    <van-col span="8">件数合计: {{parseFloat(fzslhj).toFixed(1)}}</van-col>
                    <van-col span="8">金额合计: {{jehj}}</van-col>
                </van-row>
            </van-cell>
        </group>
        <group v-for="(item, index) in cps" :key="index">
            <van-cell
                    center
                    :title="item.cpms"
                    :label="'产品编号：'+item.cpbh"
                    class="cpinfo"
            >
                <van-row>
                    <van-col span="21"><van-stepper v-model="item.sl" input-width="80" min="0" /></van-col>
                    <van-col span="3"><van-icon :name="item.show === true ? 'arrow' : 'arrow-down'" @click="item.show = !item.show" /></van-col>
                </van-row>
            </van-cell>
            <van-cell>
                <van-row>
                    <van-col span="12">装箱数: {{parseFloat(item.zhxs).toFixed()}}</van-col>
                    <van-col span="12">件数: {{parseFloat(item.sl/item.zhxs).toFixed(1)}}</van-col>
                </van-row>
            </van-cell>
            <van-cell v-if="item.show === true">
                <van-row>
                    <van-col span="8">单价: {{parseFloat(item.scj).toFixed(2)}}</van-col>
                    <van-col span="8">金额: {{parseFloat(item.scj*item.sl).toFixed((2))}}</van-col>
                    <van-col span="8">库存箱数: {{parseFloat(item.kcsl/item.zhxs).toFixed(1)}}</van-col>
                </van-row>
            </van-cell>
            <van-field
                    v-model="item.hbz"
                    label="备注"
                    type="textarea"
                    placeholder="请输入备注"
                    rows="1"
                    autosize
                    right-icon="delete"
                    @click-right-icon="deleteItem(index)"
                    v-if="item.show === true"
            />
        </group>
        <group>
        <!--<van-button type="primary" size="large" @click="scanPro">扫码</van-button>-->
            <van-field
                    v-model="searchCpbh"
                    center
                    clearable
                    label="产品编号"
                    right-icon="scan"
                    @click-right-icon="scanPro"
                    placeholder="请输入产品编号"
            >
                <van-button slot="button" size="small" @click="getProInfoByBh" type="primary">获取产品信息</van-button>
            </van-field>
        </group>
        <group>
        <van-button type="primary" size="large" @click="orderAdd">提交</van-button>
        </group>
    </div>
</template>
<script>
  import { customerList, getJssdkConfig, getProInfo, orderAdd } from '@/api'
  import { Field, Button, Cell, CellGroup, NavBar, RadioGroup, Radio, Stepper, Toast, Row, Col, Icon } from 'vant'
  import { Datetime, Group, XTable, PopupPicker, Picker } from 'vux'
  import Multiselect from 'vue-multiselect'
  import { Select, Option } from 'element-ui'
  // import wx from '../assets/js/jweixin-1.4.0.js'
  const wx = require('weixin-js-sdk')

  export default {
    components: {
      Multiselect,
      Picker,
      Datetime,
      PopupPicker,
      Group,
      XTable,
      [Select.name]: Select,
      [Option.name]: Option,
      [Field.name]: Field,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [NavBar.name]: NavBar,
      [RadioGroup.name]: RadioGroup,
      [Radio.name]: Radio,
      [Stepper.name]: Stepper,
      [Row.name]: Row,
      [Col.name]: Col,
      [Icon.name]: Icon,
      [Button.name]: Button
    },
    data () {
      return {
        jhrq: '', // 交货日期
        khbh: '', // 客户编号
        fkfs: [], // 付款方式
        fkfsOptions: [[
          '未结账',
          '已付现金',
          '已刷卡',
          '已汇款',
          '等汇款',
          '货到付款',
          '换货',
          '未付清'
        ]],
        khOptions: [],
        bz: '', // 备注
        cps: [], // 产品
        khLoading: false,
        slhj: 0,
        fzslhj: 0,
        jehj: 0,
        barcode: '',
        searchCpbh: ''
      }
    },
    watch: {
      cps: {
        handler (value) {
          this.slhj = 0
          this.fzslhj = 0
          this.jehj = 0
          for (let i in value) {
            this.slhj += value[i].sl
            this.fzslhj += parseFloat(value[i].sl / value[i].zhxs).toFixed(2) * 1
            this.jehj += (value[i].sl * value[i].scj).toFixed(2) * 1
          }
        },
        deep: true
      }
    },
    methods: {
      customerList (query) {
        let data = {keyword: query}
        this.khLoading = true
        customerList(data).then((res) => {
          if (res.code === 200) {
            console.log(res)
            this.khOptions = res.data
          }
          this.khLoading = false
        })
      },
      onBack () {
        this.$router.back()
      },
      dateCancel () {
        this.datetime = ''
      },
      orderAdd () {
        let data = {
          jhrq: this.jhrq,
          khbh: this.khbh,
          fkfs: this.fkfs,
          cps: this.cps,
          bz: this.bz
        }
        orderAdd(data).then((res) => {
          if (res.code === 200) {
            Toast('添加成功')
            this.$router.push({path: '/'})
          } else {
            Toast('添加失败')
          }
        })
      },
      scanPro () {
        if (process.env.NODE_ENV !== 'production') {
          // this.getProInfo('465478946548')
          // this.barcode = '000523'
          this.barcode = '007328'
          let param = {cptm: this.barcode}
          this.getProInfo(param)
          return
        }
        wx.scanQRCode({
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          scanType: ['barCode'], // ['qrCode', 'barCode']可以指定扫二维码还是一维码，默认二者都有
          success: (res) => {
            var result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
            // result = '128,000523'
            var code = result.split(',')
            this.barcode = code[1]
            let param = {cptm: this.barcode}
            this.getProInfo(param)
          }
        })
      },
      getProInfo (param) {
        getProInfo(param).then((res) => {
          if (!res.data) {
            Toast('没有找到相应产品-条码' + this.barcode)
          }

          for (let i in this.cps) {
            if (this.cps[i].code === res.data.cptm) {
              Toast('产品已添加，请勿重复操作！')
              return
            }
          }
          res.data.sl = 0
          res.data.code = res.data.cptm
          res.data.hbz = ''
          res.data.show = true
          this.cps.push(res.data)
          // this.cps.push({cpms: res.data.cpms, sl: 1, cpbh: res.data.cpbh, zhxs: res.data.zhxs, scj: res.data.scj, hbz: '', code: code})
        })
      },
      getProInfoByBh () {
        let param = {cpbh: this.searchCpbh}
        this.getProInfo(param)
      },
      focusKh () {
        this.$refs.khmcRef.focus()
      },
      deleteItem (index) {
        this.cps.splice(index, 1)
      }
    },
    mounted () {
      getJssdkConfig(location.href.split('#')[0]).then((res) => {
        wx.config(
          res.data.config
        )
      })
      this.$refs.khmcRef.focus()
    }
  }
</script>
<style>
    .cpinfo{
        background-color: #c0f0ef;
    }
</style>
